//
//  ProductDetailViewController.m
//  Tiger
//
//  Created by King on 11-10-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "CollectionViewController.h"
#import "ProductDetailViewCell.h"

#import <QuartzCore/QuartzCore.h>

#define kProductDescription		@"productDescription"
#define kProduct_Name			@"productName"
#define kMode					@"mode"
#define kSize					@"size"

#define kCustomRowCount     5

#define LabelW 260

@implementation ProductDetailViewController


@synthesize productID;
@synthesize myImageView;
//@synthesize activity;
@synthesize nameLable, descrTextView;
@synthesize parsedDataArray, noteDataList;
@synthesize tableView;



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"订购"
																			   style:UIBarButtonItemStyleDone
																			  target:self
																			  action:@selector(collectionButtonTapped:)] autorelease];
	[self sendRequestPayInfo];
	//[self.activity startAnimating];
    myImageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 120)];
    [self.view addSubview:myImageView];
    
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 120, 320, 266) style:UITableViewStylePlain];
    tableView.separatorStyle = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    
    p_TableBGView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 266)];
    [p_TableBGView setImage:[UIImage imageNamed:@"screen_bg.png"]];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
    UIView* tHeadView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 126)];
    [tHeadView setBackgroundColor:[UIColor clearColor]];
    nameLable = [[UILabel alloc] initWithFrame:CGRectMake(26, 6, 290, 20)];
    [nameLable setTextColor:[UIColor whiteColor]];
    [nameLable setBackgroundColor:[UIColor clearColor]];
    [nameLable setFont:[UIFont boldSystemFontOfSize:14.f]];
    [tHeadView addSubview:nameLable];
    descrTextView = [[UITextView alloc] initWithFrame:CGRectMake(18, 26, 278, 100)];
    [descrTextView setBackgroundColor:[UIColor clearColor]];
    [descrTextView setTextColor:[UIColor whiteColor]];
    [descrTextView setFont:[UIFont systemFontOfSize:14.f]];
    descrTextView.userInteractionEnabled = NO;
    //descrTextView.textAlignment = UITextAlignmentCenter;
    [tHeadView addSubview:descrTextView];
    tableView.tableHeaderView =tHeadView;
    [tHeadView release];
    
}

- (void)sendRequestPayInfo{
	//GET 请求

	NSString *getURL = [NSString stringWithFormat:@"http://www.speedtiger.com.cn/ios3/product_detail.html?id=%d",productID];
	NSLog(@"%@", getURL);
	ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:getURL]];
	request.tag = -1;
	[request setValidatesSecureCertificate:NO];
	[request setDelegate:self];
	[request startAsynchronous];

}


#pragma mark ASIHTTPRequestDelegate methods
- (void)requestStarted:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}


- (void)requestFinished:(ASIHTTPRequest *)request;
{
	NSData *responseData = [request responseData];
	NSString *responseStr = [[[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] autorelease];
	if (request.tag < 0) 
	{
		NSDictionary *dict = [responseStr JSONValue];
		NSString *picURL = [dict objectForKey:@"picUrl"] ;
		if(picURL){
			NSURL *url=[NSURL URLWithString:picURL];
			[myImageView setImageWithURL:url];
			//[self.activity stopAnimating]; 
		}
		nameLable.text = [dict objectForKey:kProduct_Name];
		descrTextView.text = [dict objectForKey:kProductDescription] ;
		NSDictionary *root = [dict objectForKey:@"models"];
		self.parsedDataArray = [root objectForKey:@"items"];
        p_Material = [dict objectForKey:@"material"] ;
        [p_Material retain];
        p_Character= [dict objectForKey:@"character"] ;
        [p_Character retain];
        
        

        CGSize tMatsize = [p_Material sizeWithFont:[UIFont systemFontOfSize:13]];
        
        int htrow = (int)tMatsize.width %LabelW == 0? tMatsize.width/LabelW:tMatsize.width/LabelW+1;
        p_MatH =htrow * tMatsize.height;
        
        CGSize tCharsize = [p_Character sizeWithFont:[UIFont systemFontOfSize:13]];
        htrow = (int)tCharsize.width %LabelW == 0? tCharsize.width/LabelW:tCharsize.width/LabelW+1;
        
        p_CharH = htrow *tCharsize.height;
        
		[self.tableView reloadData];
		isCollection = YES;
        
	}
	else {
		NSLog(@"recved bad data !");
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	//[self.activity stopAnimating]; 
	isCollection = NO;
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"无可用的网络连接" delegate:self 
										   cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
	[alert addButtonWithTitle:@"确定"];
	[alert show];
	
}

- (IBAction)backButtonTapped:(id)sender{
	
	[self.navigationController popViewControllerAnimated:YES];
	
}

- (IBAction)collectionButtonTapped:(id)sender{
	if (isCollection) {
		NSString *proName = nameLable.text;
		//NSLog(@"proName = %@", proName);
		NSString *_productID = [NSString stringWithFormat: @"%d", self.productID];
		
		//NSLog(@"_productID = %@", _productID);
		
		
		//封装字典
		NSMutableDictionary *newdict = [[NSMutableDictionary alloc] init];
		[newdict setObject:_productID forKey:@"productID"];
		[newdict setObject:proName forKey:@"productName"];
		

		/*****************************************/
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"noteData.plist"];
		
		noteDataList = [[NSMutableArray alloc] initWithContentsOfFile:writableDBPath];
		

			//写入：
			[noteDataList addObject:newdict];
			[noteDataList writeToFile:writableDBPath atomically:YES];
			
			
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"温馨提示" 
															 message:@"订购成功" 
															delegate:self 
												   cancelButtonTitle:nil 
												   otherButtonTitles:nil] autorelease];
			[alert addButtonWithTitle:@"确定"];
			[alert show];

//		}
	}
	else 
	{
		UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"订购失败" 
														 message:@"数据尚未载入" 
														delegate:self 
											   cancelButtonTitle:nil 
											   otherButtonTitles:nil] autorelease];
		[alert addButtonWithTitle:@"确定"];
		[alert show];
	}
}


#pragma mark Table view methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int row =indexPath.row;
    if (row < 4) {
        if (row %2 ==0) {
            return 40;
        }else {
            switch (row) {
                case 1:
                    
                    return p_MatH;
                case 3:
                    
                    return p_CharH+6;
            }
        }
    }
	return 48.0;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	int count = [parsedDataArray count];
    if (count == 0)
	{
        return kCustomRowCount;
    }
    return count+5;
	
}

- (UITableViewCell *)tableView:(UITableView *)itableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    [itableView setBackgroundView:p_TableBGView];
    
    static NSString* CellIdentifier = @"Cellidentifier";
    static NSString* rowin4 = @"rowin4";
    int row = indexPath.row;
    ProductDetailViewCell *cellpro;
    UITableViewCell* cell;
    if (row < 4) {
        cell = [itableView dequeueReusableCellWithIdentifier:rowin4];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                                    reuseIdentifier:rowin4] autorelease];
            [cell setBackgroundColor:[UIColor clearColor]];
            UILabel* tSay =[[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 20)];
            [tSay setTextColor:[UIColor lightGrayColor]];
            tSay.layer.cornerRadius =1.0f;
            tSay.layer.masksToBounds =YES;
            tSay.tag =0x300;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell addSubview:tSay];
            [tSay release];
        }
    }else{
        cellpro = (ProductDetailViewCell *) [itableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cellpro == nil) {
            cellpro = [[[ProductDetailViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                                 reuseIdentifier:CellIdentifier] autorelease];
            [cellpro setBackgroundColor:[UIColor clearColor]];
        }
    }
    
		

    if (indexPath.row == 4) {
        cellpro.productNameLabel.textColor = [UIColor grayColor];
        
        cellpro.productName = @"精品型号 MODE";
		cellpro.productNameEn = @"直径d 刃长|全长L 柄径D R径 刃数Z";
        
        [cellpro.contentView setBackgroundColor:[UIColor colorWithRed:50/255.f green:50/255.f blue:50/255.f alpha:1.0f]];
        return cellpro;
    }else if (indexPath.row >= 5)
	{
        [cellpro.contentView setBackgroundColor:[UIColor clearColor]];
        cellpro.productNameLabel.textColor = [UIColor whiteColor];
		int index = indexPath.row;
		NSDictionary *dic = [parsedDataArray objectAtIndex:index-5];
		
		cellpro.productName = [dic objectForKey:kMode];
		cellpro.productNameEn = [dic objectForKey:kSize];
		cellpro.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellpro;
	}else{
        UILabel* tSay =(UILabel*)[cell viewWithTag:0x300];
        if (row%2 == 0) {
            tSay.frame = CGRectMake(26, 10, 62, 20);
            tSay.numberOfLines =1;
            tSay.textAlignment = UITextAlignmentCenter;
            [tSay setFont:[UIFont systemFontOfSize:13]];
            [tSay setBackgroundColor:[UIColor colorWithRed:90/255.f green:90/255.f blue:90/255.f alpha:1.0f]];
            
            if (row == 0) {
                [tSay setText:@"适用材料"];
            }else{
                [tSay setText:@"主要特性"];
            }
        }else{
            
            tSay.numberOfLines =10;
            tSay.textAlignment = UITextAlignmentLeft;
            [tSay setFont:[UIFont systemFontOfSize:13]];
            [tSay setBackgroundColor:[UIColor clearColor]];
            if (row == 1) {
                tSay.frame = CGRectMake(26, 2, LabelW, p_MatH);
                if ([p_Material length] > 0) {
                    [tSay setText:p_Material];
                }
                
            }else{
                tSay.frame = CGRectMake(26, 2, LabelW, p_CharH);
                if ([p_Character length] > 0) {
                    [tSay setText:p_Character];
                }
            }
        }
        return  cell;
    }
	return nil;
}



- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

	self.myImageView = nil;
	//self.activity = nil;
	self.nameLable = nil;
	self.descrTextView = nil;
	self.tableView = nil;
	
	
}


- (void)dealloc {
    [p_Material release];
    [p_Character release];
    [p_TableBGView release];
    [super dealloc];
	[parsedDataArray release];
	[noteDataList release];
	[tableView_ release];
	[myImageView release];
	[activity release];
	[nameLable release];
	[UITextView release];
	
}

@end
